package com.xbd.wxpay.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbd.wxpay.util.SM4Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;
import org.springframework.web.multipart.MultipartFile;

import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.cert.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/lakala")
public class LakalaController {
    /**
     * 字符集固定 utf-8
     */
    public  static   String ENCODING = "utf-8";
    /**
     * 接入 appid
     */
    public   String appid = "OP00000880";
    public String term_no ="E5326037"; //终端号
    /**
     * 商户证书序列号，和商户私钥对应
     */
    public   String mchSerialNo = "8226900739201UP"; //商户号

    public String serial_no="01752b7386f8"; //证书序列号

    public static String SCHEMA = "LKLAPI-SHA256withRSA";

    //分隔符
    public static  String       MARK_SUBTRACTION                = "-";
    //分隔符
    public static  String       MARK_COMMA                      = ",";
    //分隔符
    public static  String       MARK_EQUEL                      = "=";

    private  final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private  final SecureRandom RANDOM = new SecureRandom();
    private String getJarFilePath() {
        ApplicationHome home = new ApplicationHome(getClass());
        File jarFile = home.getSource();
        return jarFile.getParentFile().toString();
    }

    protected String generateNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }
    protected long generateTimestamp() {
        return System.currentTimeMillis() / 1000;
    }

    public String sign(byte[] message, PrivateKey privateKey) {
        try {
            Signature sign = Signature.getInstance("SHA256withRSA");
            sign.initSign(privateKey);
            sign.update(message);
            return new String(Base64.encodeBase64(sign.sign()));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("当前Java环境不支持SHA256withRSA", e);
        } catch (SignatureException e) {
            throw new RuntimeException("签名计算失败", e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException("无效的私钥", e);
        }
    }
    public  String getAuthorization(String nonceStr,long timestamp,String body) throws IOException {


        String message = appid + "\n" + serial_no + "\n" + timestamp + "\n" + nonceStr + "\n" + body + "\n";

        //System.out.println("getToken message :  " + message);

        File file= new File(getClass().getClassLoader().getResource("static/OP00000003_private_key.pem").getFile());
        PrivateKey merchantPrivateKey = loadPrivateKey(new FileInputStream(file));

        String signature = this.sign(message.getBytes(ENCODING), merchantPrivateKey);

        String authorization = "appid=\"" + appid + "\"," + "serial_no=\"" + serial_no + "\"," + "timestamp=\""
                + timestamp + "\"," + "nonce_str=\"" + nonceStr + "\"," + "signature=\"" + signature + "\"";
        //  System.out.println("authorization message :" + authorization);

        return authorization;
    }

    @RequestMapping(method = RequestMethod.GET,value = "/pay")
    public String pay() throws Exception {

        long timestamp =generateTimestamp();
        String nonceStr = generateNonceStr();

        JSONObject acc_busi_fields  = new JSONObject();
        acc_busi_fields.put("user_id","oJoMX5a-6BdDSTRkWEWMm4rQgiFk"); //小程序openid

        JSONObject location_info  = new JSONObject();
        location_info.put("request_ip","127.0.0.1");

        JSONObject jsonObject  = new JSONObject();
        jsonObject.put("merchant_no",mchSerialNo);
        jsonObject.put("term_no",term_no);
        jsonObject.put("notify_url","");  //回调地址
        jsonObject.put("settle_type","1");//0”或者空，常规结算方式，如需接拉卡拉分账需传“1”；
        jsonObject.put("out_trade_no","FD660E1FAA3A4470933CDEDAE1EC1Dff");
        jsonObject.put("account_type","WECHAT");
        jsonObject.put("trans_type","71"); //71:微信小程序支付 51:JSAPI（微信公众号支付
        jsonObject.put("total_amount","1");
        jsonObject.put("location_info",location_info);
        jsonObject.put("acc_busi_fields",acc_busi_fields);

        Date now = new Date();
        // 创建日期时间格式化器
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        // 将日期时间对象格式化为字符串
        String formattedDateTime = formatter.format(now);
        JSONObject body  = new JSONObject();
        body.put("out_org_code",appid);
        body.put("req_data",jsonObject);
        body.put("req_time",formattedDateTime);
        body.put("version","3.0");


        System.out.println(body.toJSONString());
        String apiUrl = "https://s2.lakala.com/api/v3/labs/trans/preorder";


        String authorization = getAuthorization(nonceStr,timestamp,body.toJSONString());
        System.out.println("authorization"+authorization);
        HttpResponse response = post(apiUrl , body.toJSONString(), authorization);


        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // 将响应实体转换为字符串
            String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            System.out.println("ff"+responseBody);
            // 打印输出响应体
            return  responseBody;
        }else{
            return  "";
        }
    }

    //分账信息查询
    @RequestMapping(method = RequestMethod.GET,value = "/info")
    public String info() throws Exception {

        long timestamp =generateTimestamp();
        String nonceStr = generateNonceStr();



        JSONObject jsonObject  = new JSONObject();
        jsonObject.put("version","1.0");
        jsonObject.put("orderNo","FD660E1FAA3A4470933CDEDAE1EC1D02");//订单编号（便于后续跟踪排查问题及核对报文）	14位年月日时（24小时制）分秒+8位的随机数（不重复）如：2021020112000012345678
        jsonObject.put("orgCode","968855");//机构代码
        jsonObject.put("merCupNo",mchSerialNo); //银联商户号


        Date now = new Date();
        // 创建日期时间格式化器
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        // 将日期时间对象格式化为字符串
        String formattedDateTime = formatter.format(now);
        JSONObject body  = new JSONObject();

        body.put("reqData",jsonObject);
        body.put("reqId","KFPT20230223181747812863750");
        body.put("version","2.0");
        body.put("reqTime",formattedDateTime);

        System.out.println(body.toJSONString());
        String apiUrl = "https://s2.lakala.com/api/v2/mms/openApi/ledger/queryLedgerMer";
        String str = body.toJSONString();
        String authorization = getAuthorization(nonceStr,timestamp,str);
        System.out.println("authorization"+authorization);
        HttpResponse response = post(apiUrl , str, authorization);


        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // 将响应实体转换为字符串
            String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            System.out.println("ff"+responseBody);
            // 打印输出响应体
            return  responseBody;
        }else{
            return  "";
        }
    }

    //账户余额查询
    @RequestMapping(method = RequestMethod.GET,value = "/yue")
    public String yue() throws Exception {

        long timestamp =generateTimestamp();
        String nonceStr = generateNonceStr();
        JSONObject jsonObject  = new JSONObject();
        jsonObject.put("orgNo","968855"); //机构号
        jsonObject.put("merchantNo",mchSerialNo); //商户号
        Date now = new Date();
        // 创建日期时间格式化器
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        // 将日期时间对象格式化为字符串
        String formattedDateTime = formatter.format(now);
        JSONObject body  = new JSONObject();

        body.put("reqData",jsonObject);
        body.put("reqId","KFPT20230223181747812863750");  //请求序列号 32位
        body.put("ver","1.0.0");
        body.put("timestamp",formattedDateTime);  //Unix时间戳。13位


        System.out.println(body.toJSONString());
        String apiUrl = "https://s2.lakala.com/api/v2/laep/industry/ewalletBalanceQuery";

        String str = body.toJSONString();
        String authorization = getAuthorization(nonceStr,timestamp,str);
        System.out.println("authorization"+authorization);
        HttpResponse response = post(apiUrl , str, authorization);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 将响应实体转换为字符串
            String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            System.out.println("ff"+responseBody);
            // 打印输出响应体
            return  responseBody;
        }else{
            return  "";
        }
    }

    //分账接收方创建申请
    @RequestMapping(method = RequestMethod.GET,value = "/join")
    public String join() throws Exception {

        long timestamp =generateTimestamp();
        String nonceStr = generateNonceStr();
        JSONObject jsonObject  = new JSONObject();
        jsonObject.put("version","1.0");
        jsonObject.put("orderNo","KFPT20230223181747812863751");
        jsonObject.put("orgCode","1");
        jsonObject.put("receiverName","杨少东");
        jsonObject.put("contactMobile","13402943541");

        jsonObject.put("acctNo","6214852901831845");
        jsonObject.put("acctName","杨少东");
        jsonObject.put("acctTypeCode","58");//57：对公 58：对私
        jsonObject.put("acctCertificateType","17");//17 身份证，18 护照，19 港澳居民来往内地通行证 20 台湾居民来往内地通行
        jsonObject.put("acctCertificateNo","610121199009077277");
        jsonObject.put("acctOpenBankCode","308791011217");
        jsonObject.put("acctOpenBankName","招商银行");



        JSONObject jsonObject1  = new JSONObject();
        jsonObject1.put("attachName","身份证"); //
        jsonObject1.put("attachStorePath","G1/M00/02/91/CrFdEV78VhWAQCdHAAKuX4eCfyY748.jpg"); //
        jsonObject1.put("attachType","ID_CARD_FRONT"); //

        JSONObject jsonObject2  = new JSONObject();
        jsonObject2.put("attachName","银行卡"); //
        jsonObject2.put("attachStorePath","G1/M00/02/91/CrFdEV78VhWAQCdHAAKuX4eCfyY748.jpg"); //
        jsonObject2.put("attachType","BANK_CARD"); //



        JSONArray jsonArray = new JSONArray();
        jsonArray.add(jsonObject1);
        jsonArray.add(jsonObject2);



        jsonObject.put("attachList",jsonArray);



        Date now = new Date();
        // 创建日期时间格式化器
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        // 将日期时间对象格式化为字符串
        String formattedDateTime = formatter.format(now);
        JSONObject body  = new JSONObject();

        body.put("reqData",jsonObject);
        body.put("reqId","KFPT20230223181747812863750");  //请求序列号 32位
        body.put("version","2.0");
        body.put("reqTime",formattedDateTime);  //Unix时间戳。13位


        System.out.println(body.toJSONString());
        String apiUrl = "https://s2.lakala.com/sit/api/v2/mms/openApi/ledger/applyLedgerReceiver";

        String str = body.toJSONString();
        String authorization = getAuthorization(nonceStr,timestamp,str);
        System.out.println("authorization"+authorization);
        HttpResponse response = post(apiUrl , str, authorization);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 将响应实体转换为字符串
            String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            System.out.println("ff"+responseBody);
            // 打印输出响应体
            return  responseBody;
        }else{
            return  "";
        }
    }

    //分账接收方创建申请
    @RequestMapping(method = RequestMethod.GET,value = "/bind")
    public String bind() throws Exception {

        long timestamp =generateTimestamp();
        String nonceStr = generateNonceStr();
        JSONObject jsonObject  = new JSONObject();
        jsonObject.put("version","1.0");
        jsonObject.put("orderNo","KFPT20230223181747812863751");
        jsonObject.put("orgCode","1");
        jsonObject.put("merCupNo","822290058120N51");


        jsonObject.put("receiverNo","SR2023072417013");
        jsonObject.put("entrustFileName","杨少东");
        jsonObject.put("entrustFilePath","58");//57：对公 58：对私
        jsonObject.put("retUrl","http://xxxxx"); //回调地址




        Date now = new Date();
        // 创建日期时间格式化器
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        // 将日期时间对象格式化为字符串
        String formattedDateTime = formatter.format(now);
        JSONObject body  = new JSONObject();

        body.put("reqData",jsonObject);
        body.put("reqId","KFPT20230223181747812863750");  //请求序列号 32位
        body.put("version","2.0");
        body.put("reqTime",formattedDateTime);  //Unix时间戳。13位


        System.out.println(body.toJSONString());
        String apiUrl = "https://s2.lakala.com/sit/api/v2/mms/openApi/ledger/applyBind";

        String str = body.toJSONString();
        String authorization = getAuthorization(nonceStr,timestamp,str);
        System.out.println("authorization"+authorization);
        HttpResponse response = post(apiUrl , str, authorization);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 将响应实体转换为字符串
            String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            System.out.println("ff"+responseBody);
            // 打印输出响应体
            return  responseBody;
        }else{
            return  "";
        }
    }
    //分账接收方创建申请
    @RequestMapping(method = RequestMethod.GET,value = "/bind/search")
    public String bindSearch() throws Exception {

        long timestamp =generateTimestamp();
        String nonceStr = generateNonceStr();
        JSONObject jsonObject  = new JSONObject();
        jsonObject.put("version","1.0");
        jsonObject.put("orderNo","KFPT20230223181747812863751");
        jsonObject.put("orgCode","1");
        jsonObject.put("merCupNo","822290058120N51");


        jsonObject.put("receiverNo","SR2023072417013");
        jsonObject.put("entrustFileName","杨少东");
        jsonObject.put("entrustFilePath","58");//57：对公 58：对私
        jsonObject.put("retUrl","http://xxxxx"); //回调地址




        Date now = new Date();
        // 创建日期时间格式化器
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        // 将日期时间对象格式化为字符串
        String formattedDateTime = formatter.format(now);
        JSONObject body  = new JSONObject();

        body.put("reqData",jsonObject);
        body.put("reqId","KFPT20230223181747812863750");  //请求序列号 32位
        body.put("version","2.0");
        body.put("reqTime",formattedDateTime);  //Unix时间戳。13位


        System.out.println(body.toJSONString());
        String apiUrl = "https://s2.lakala.com/sit/api/v2/mms/openApi/ledger/applyBind";

        String str = body.toJSONString();
        String authorization = getAuthorization(nonceStr,timestamp,str);
        System.out.println("authorization"+authorization);
        HttpResponse response = post(apiUrl , str, authorization);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 将响应实体转换为字符串
            String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            System.out.println("ff"+responseBody);
            // 打印输出响应体
            return  responseBody;
        }else{
            return  "";
        }
    }
    //余额提现
    @RequestMapping(method = RequestMethod.GET,value = "/tixian")
    public String tixian() throws Exception {

        long timestamp =generateTimestamp();
        String nonceStr = generateNonceStr();
        JSONObject jsonObject  = new JSONObject();
        jsonObject.put("merchant_no","822290058120N51");

        jsonObject.put("cal_type","0"); //0- 按照指定金额，1- 按照指定比例。默认 0
        jsonObject.put("notify_url","");
        jsonObject.put("out_separate_no","KFPT20230223181747812863751");
        jsonObject.put("total_amt","100");

        JSONArray recv_datas = new JSONArray();

        JSONObject jsonObject1  = new JSONObject();
        jsonObject1.put("recv_merchant_no","822290058120N51");
        jsonObject1.put("separate_value","30");

        JSONObject jsonObject2  = new JSONObject();
        jsonObject2.put("recv_no","SR2023072417013");
        jsonObject2.put("separate_value","70");

        recv_datas.add(jsonObject1);
        recv_datas.add(jsonObject2);

        jsonObject.put("recv_datas",recv_datas);


        Date now = new Date();
        // 创建日期时间格式化器
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        // 将日期时间对象格式化为字符串
        String formattedDateTime = formatter.format(now);
        JSONObject body  = new JSONObject();

        body.put("req_data",jsonObject);
        body.put("version","3.0");
        body.put("req_time",formattedDateTime);  //Unix时间戳。13位


        System.out.println(body.toJSONString());
        String apiUrl = "https://s2.lakala.com/sit/api/v3/sacs/balanceSeparate";

        String str = body.toJSONString();
        String authorization = getAuthorization(nonceStr,timestamp,str);
        System.out.println("authorization"+authorization);
        HttpResponse response = post(apiUrl , str, authorization);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 将响应实体转换为字符串
            String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            System.out.println("ff"+responseBody);
            // 打印输出响应体
            return  responseBody;
        }else{
            return  "";
        }
    }

    //商户分账业务开通申请
    @RequestMapping(method = RequestMethod.GET,value = "/open")
    public String open() throws Exception {

        // mchSerialNo="822290058120N51";
        //term_no="F0166806";

        // appid= "OP00000733";

        long timestamp =generateTimestamp();
        String nonceStr = generateNonceStr();
        JSONObject jsonObject  = new JSONObject();
        jsonObject.put("version","1.0");
        jsonObject.put("orderNo","KFPT20230223181747812863751");
        jsonObject.put("orgCode","968855");
        // jsonObject.put("orgCode","1");
        jsonObject.put("merCupNo",mchSerialNo);
//        jsonObject.put("merCupNo","1");
        jsonObject.put("contactMobile","13992853452");
        jsonObject.put("splitLowestRatio","30.0");
        jsonObject.put("splitEntrustFileName","分账结算委托书文件名称.jpg");
        jsonObject.put("splitEntrustFilePath","G5/M03/8B/6D/ChIKL2TDUZ6AE_l2AAXL1X2wIfE192.jpg");
        jsonObject.put("retUrl","http://www.sanqinjiabao.com/test.php"); //回调地址


        Date now = new Date();
        // 创建日期时间格式化器
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        // 将日期时间对象格式化为字符串
        String formattedDateTime = formatter.format(now);
        JSONObject body  = new JSONObject();

        body.put("reqData",jsonObject);
        body.put("reqId","KFPT20230223181747812863750");  //请求序列号 32位
        body.put("version","2.0");
        body.put("reqTime",formattedDateTime);  //Unix时间戳。13位


        System.out.println(body.toJSONString());
        String apiUrl = "https://s2.lakala.com/api/v2/mms/openApi/ledger/applyLedgerMer";
        // apiUrl= "https://test.wsmsd.cn/sit/api/v2/mms/openApi/ledger/applyLedgerMer";


        String str = body.toJSONString();
        String authorization = getAuthorization(nonceStr,timestamp,str);
        System.out.println("authorization"+authorization);
        HttpResponse response = post(apiUrl , str, authorization);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 将响应实体转换为字符串
            String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            System.out.println("ff"+responseBody);
            // 打印输出响应体
            return  responseBody;
        }else{
            return  "";
        }
    }

    @PostMapping("/upload")
    public String upload(@RequestParam("image") MultipartFile image) throws Exception {

        byte[] bytes = image.getBytes();
        String base64Image = Base64.encodeBase64String(bytes);

        long timestamp =generateTimestamp();
        String nonceStr = generateNonceStr();
        JSONObject jsonObject  = new JSONObject();
        jsonObject.put("version","1.0");
        jsonObject.put("orderNo","KFPT20230223181747812863751");
//        jsonObject.put("orgCode","1");
        jsonObject.put("orgCode","968855");//机构代码

        jsonObject.put("attType","XY");
        jsonObject.put("attExtName","jpg");
        jsonObject.put("attContext", base64Image); //回调地址


        Date now = new Date();
        // 创建日期时间格式化器
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        // 将日期时间对象格式化为字符串
        String formattedDateTime = formatter.format(now);
        JSONObject body  = new JSONObject();

        body.put("reqData",jsonObject);
        body.put("reqId","KFPT20230223181747812863750");  //请求序列号 32位
        body.put("ver","1.0.0");
        body.put("timestamp",formattedDateTime);  //Unix时间戳。13位


        System.out.println(body.toJSONString());
        String apiUrl = "https://s2.lakala.com/api/v2/mms/openApi/uploadFile";
        //  apiUrl ="https://test.wsmsd.cn/sit/api/v2/mms/openApi/uploadFile";
        // appid= "OP00000733";

        String str = body.toJSONString();
        String authorization = getAuthorization(nonceStr,timestamp,str);
        System.out.println("authorization"+authorization);
        HttpResponse response = post(apiUrl , str, authorization);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 将响应实体转换为字符串
            String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            System.out.println("ff"+responseBody);
            // 打印输出响应体
            return  responseBody;
        }else{
            return  "";
        }
    }

    //订单查询
    @RequestMapping(method = RequestMethod.GET,value = "/order/search")
    public String orderSearch() throws Exception {

//        mchSerialNo="8221210594300JY";
//        term_no="A0073841";
//
//        appid="OP00000733";


        long timestamp =generateTimestamp();
        String nonceStr = generateNonceStr();
        JSONObject jsonObject  = new JSONObject();

        jsonObject.put("merchant_no",mchSerialNo);
        jsonObject.put("term_no",term_no);
        jsonObject.put("out_trade_no","FD660E1FAA3A4470933CDEDAE1EC1Dff");



        Date now = new Date();
        // 创建日期时间格式化器
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        // 将日期时间对象格式化为字符串
        String formattedDateTime = formatter.format(now);
        JSONObject body  = new JSONObject();

        body.put("req_data",jsonObject);
        body.put("out_org_code","KFPT20230223181747812863750");  //请求序列号 32位
        body.put("version","3.0");
        body.put("req_time",formattedDateTime);  //Unix时间戳。13位


        System.out.println(body.toJSONString());
        String apiUrl = "https://s2.lakala.com/api/v3/labs/query/tradequery";
        //  apiUrl= "https://test.wsmsd.cn/sit/api/v3/labs/query/tradequery";


        String str = body.toJSONString();
        String authorization = getAuthorization(nonceStr,timestamp,str);
        System.out.println("authorization"+authorization);
        HttpResponse response = post(apiUrl , str, authorization);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 将响应实体转换为字符串
            String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            System.out.println("ff"+responseBody);
            // 打印输出响应体
            return  responseBody;
        }else{
            return  "";
        }
    }

    //分账结果查询
    @RequestMapping(method = RequestMethod.GET,value = "/fenzhang/search")
    public String fenzhangSearch() throws Exception {

//        mchSerialNo="8221210594300JY";
//        term_no="A0073841";
//        appid="OP00000733";


        long timestamp =generateTimestamp();
        String nonceStr = generateNonceStr();
        JSONObject jsonObject  = new JSONObject();

        jsonObject.put("merchant_no",mchSerialNo);
        jsonObject.put("out_separate_no","13992853452");



        Date now = new Date();
        // 创建日期时间格式化器
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        // 将日期时间对象格式化为字符串
        String formattedDateTime = formatter.format(now);
        JSONObject body  = new JSONObject();

        body.put("req_data",jsonObject);
        body.put("version","3.0");
        body.put("req_time",formattedDateTime);  //Unix时间戳。13位


        System.out.println(body.toJSONString());
        String apiUrl = "https://s2.lakala.com/api/v3/sacs/query";
        // apiUrl= "https://test.wsmsd.cn/sit/api/v3/sacs/query";


        String str = body.toJSONString();
        String authorization = getAuthorization(nonceStr,timestamp,str);
        System.out.println("authorization"+authorization);
        HttpResponse response = post(apiUrl , str, authorization);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 将响应实体转换为字符串
            String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            System.out.println("ff"+responseBody);
            // 打印输出响应体
            return  responseBody;
        }else{
            return  "";
        }
    }
    @RequestMapping(method = RequestMethod.GET,value = "/app/pay")
    public String appPay() throws Exception {

//        mchSerialNo="8221210594300JY";
//        term_no="A0073841";
//
//        appid="OP00000733";

        Date now = new Date();
        // 创建日期时间格式化器
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        // 将日期时间对象格式化为字符串
        String formattedDateTime = formatter.format(now);

        long timestamp =generateTimestamp();
        String nonceStr = generateNonceStr();

        JSONObject acc_busi_fields  = new JSONObject();
        acc_busi_fields.put("user_id","oJoMX5a-6BdDSTRkWEWMm4rQgiFk"); //小程序openid

        JSONObject location_info  = new JSONObject();
        location_info.put("request_ip","127.0.0.1");

        JSONObject jsonObject  = new JSONObject();
        jsonObject.put("merchant_no",mchSerialNo);
        jsonObject.put("term_no",term_no);
        jsonObject.put("notify_url","");  //回调地址
        jsonObject.put("settle_type","1");//0”或者空，常规结算方式，如需接拉卡拉分账需传“1”；
        jsonObject.put("out_order_no","FD660E1FAA3A4470933CDEDAE1EC1D51");
        jsonObject.put("order_efficient_time",formattedDateTime);
        jsonObject.put("trans_type","71"); //71:微信小程序支付 51:JSAPI（微信公众号支付
        jsonObject.put("total_amount","1");
        jsonObject.put("location_info",location_info);
        jsonObject.put("acc_busi_fields",acc_busi_fields);


        JSONObject body  = new JSONObject();
        body.put("out_org_code",appid);
        body.put("req_data",jsonObject);
        body.put("req_time",formattedDateTime);
        body.put("version","3.0");


        System.out.println(body.toJSONString());
        String apiUrl = "https://s2.lakala.com/api/v3/ccss/counter/order/create";
        //apiUrl="https://test.wsmsd.cn/sit/api/v3/ccss/counter/order/create";


        String authorization = getAuthorization(nonceStr,timestamp,body.toJSONString());
        System.out.println("authorization"+authorization);
        HttpResponse response = post(apiUrl , body.toJSONString(), authorization);


        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // 将响应实体转换为字符串
            String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            System.out.println("ff"+responseBody);
            // 打印输出响应体
            return  responseBody;
        }else{
            return  "";
        }
    }

    //订单查询
    @RequestMapping(method = RequestMethod.GET,value = "/app/order/search")
    public String appOrderSearch() throws Exception {

//        mchSerialNo="8221210594300JY";
//        term_no="A0073841";
//
//        appid="OP00000733";


        long timestamp =generateTimestamp();
        String nonceStr = generateNonceStr();
        JSONObject jsonObject  = new JSONObject();

        jsonObject.put("merchant_no",mchSerialNo);
        jsonObject.put("pay_order_no","FD660E1FAA3A4470933CDEDAE1EC1D51");



        Date now = new Date();
        // 创建日期时间格式化器
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        // 将日期时间对象格式化为字符串
        String formattedDateTime = formatter.format(now);
        JSONObject body  = new JSONObject();

        body.put("req_data",jsonObject);
        body.put("out_org_code","FD660E1FAA3A4470933CDEDAE1EC1D51");  //请求序列号 32位
        body.put("version","3.0");
        body.put("req_time",formattedDateTime);  //Unix时间戳。13位


        System.out.println(body.toJSONString());
        String apiUrl = "https://s2.lakala.com/api/v3/ccss/counter/order/query";
        // apiUrl= "https://test.wsmsd.cn/sit/api/v3/ccss/counter/order/query";


        String str = body.toJSONString();
        String authorization = getAuthorization(nonceStr,timestamp,str);
        System.out.println("authorization"+authorization);
        HttpResponse response = post(apiUrl , str, authorization);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 将响应实体转换为字符串
            String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            System.out.println("ff"+responseBody);
            // 打印输出响应体
            return  responseBody;
        }else{
            return  "";
        }
    }

    //账管家提现结果查询
    @RequestMapping(method = RequestMethod.GET,value = "/zhang/search")
    public String zhangSearch() throws Exception {

//        mchSerialNo="8221210594300JY";
//        term_no="A0073841";
//        appid="OP00000733";


        long timestamp =generateTimestamp();
        String nonceStr = generateNonceStr();
        JSONObject jsonObject  = new JSONObject();

        jsonObject.put("merchantNo",mchSerialNo);
        jsonObject.put("merOrderNo","8221000581200BS");
        jsonObject.put("orgNo","968855");

//        jsonObject.put("orgNo","1");



        Date now = new Date();
        // 创建日期时间格式化器
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        // 将日期时间对象格式化为字符串
        String formattedDateTime = formatter.format(now);
        JSONObject body  = new JSONObject();
        body.put("reqId","KFPT20230223181747812863750");
        body.put("reqData",jsonObject);
        body.put("ver","1.0.0");
        body.put("timestamp",formattedDateTime);  //Unix时间戳。13位


        System.out.println(body.toJSONString());
        String apiUrl = "https://s2.lakala.com/api/v2/laep/industry/ewalletWithdrawQuery";
       //  apiUrl= "https://test.wsmsd.cn/sit/api/v2/laep/industry/ewalletWithdrawQuery";


        String str = body.toJSONString();
        String authorization = getAuthorization(nonceStr,timestamp,str);
        System.out.println("authorization"+authorization);
        HttpResponse response = post(apiUrl , str, authorization);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 将响应实体转换为字符串
            String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            System.out.println("ff"+responseBody);
            // 打印输出响应体
            return  responseBody;
        }else{
            return  "";
        }
    }


    //余额分账结果查询
    @RequestMapping(method = RequestMethod.GET,value = "/balanceSeparateQuery")
    public String balanceSeparateQuery() throws Exception {

        mchSerialNo="8221210594300JY";
        term_no="A0073841";
        appid="OP00000733";


        long timestamp =generateTimestamp();
        String nonceStr = generateNonceStr();
        JSONObject jsonObject  = new JSONObject();

        jsonObject.put("merchant_no",mchSerialNo);
        jsonObject.put("out_separate_no","8221000581200BS");

//        jsonObject.put("orgNo","1");



        Date now = new Date();
        // 创建日期时间格式化器
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        // 将日期时间对象格式化为字符串
        String formattedDateTime = formatter.format(now);
        JSONObject body  = new JSONObject();

        body.put("req_data",jsonObject);
        body.put("version","3.0");
        body.put("req_time",formattedDateTime);  //Unix时间戳。13位


        System.out.println(body.toJSONString());
        String apiUrl = "https://s2.lakala.com/api/v3/sacs/balanceSeparateQuery";
          apiUrl= "https://test.wsmsd.cn/sit/api/v3/sacs/balanceSeparateQuery";


        String str = body.toJSONString();
        String authorization = getAuthorization(nonceStr,timestamp,str);
        System.out.println("authorization"+authorization);
        HttpResponse response = post(apiUrl , str, authorization);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            // 将响应实体转换为字符串
            String responseBody = EntityUtils.toString(entity, StandardCharsets.UTF_8);

            System.out.println("ff"+responseBody);
            // 打印输出响应体
            return  responseBody;
        }else{
            return  "";
        }
    }


    public  HttpResponse post(String url, String message, String authorization) throws Exception {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
            public void checkClientTrusted(X509Certificate[] xcs, String str) {}
            public void checkServerTrusted(X509Certificate[] xcs, String str) {}
        };
        HttpClient http = new DefaultHttpClient();
        ClientConnectionManager ccm = http.getConnectionManager();
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = ccm.getSchemeRegistry();
        registry.register(new Scheme("https", ssf,443));
        HttpPost post = new HttpPost(url);
        StringEntity myEntity = new StringEntity(message, ENCODING);
        post.setEntity(myEntity);
        getAuthorizationMap(SCHEMA + " " + authorization);
        post.setHeader("Authorization", SCHEMA + " " + authorization);
        post.setHeader("Accept", "application/json");
        post.setHeader("Content-Type", "application/json");
        return http.execute(post);
    }

    public static Map<String, String> getAuthorizationMap(String authorization) {
        Map<String, String> map = new HashMap<>();
        authorization = authorization.trim();
        int bpos = authorization.indexOf(" ");
        String authType = authorization.substring(0, bpos);
        String []typeArr = authType.split(MARK_SUBTRACTION);
        if(typeArr.length >1) {
            map.put("signAlgorithm", typeArr[1]);
        }
        if (typeArr.length > 2) {
            map.put("encryptAlgorithm", typeArr[2]);
        }
        String signInfo = authorization.substring(bpos + 1);
        String[] infoArr = signInfo.split(MARK_COMMA);
        for (String info : infoArr) {
            if (info.contains(MARK_EQUEL)) {
                int fpos = info.indexOf(MARK_EQUEL);
                String value = info.substring(fpos+1).trim();
                value = value.substring(1,value.length()-1);//去掉双引号
                map.put(info.substring(0,fpos).trim(),value);
            }
        }
        //System.out.println(map.toString());
        return map;
    }

    public static PrivateKey loadPrivateKey(InputStream inputStream) {
        try {
            ByteArrayOutputStream array = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                array.write(buffer, 0, length);
            }

            String privateKey = array.toString("utf-8").replace("-----BEGIN PRIVATE KEY-----", "")
                    .replace("-----END PRIVATE KEY-----", "").replaceAll("\\s+", "");
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePrivate(new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey)));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("当前Java环境不支持RSA", e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException("无效的密钥格式");
        } catch (IOException e) {
            throw new RuntimeException("无效的密钥");
        }
    }

    public static X509Certificate loadCertificate(InputStream inputStream) {
        try {
            CertificateFactory cf = CertificateFactory.getInstance("X509");
            X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);

            cert.checkValidity();
            return cert;
        } catch (CertificateExpiredException e) {
            throw new RuntimeException("证书已过期", e);
        } catch (CertificateNotYetValidException e) {
            throw new RuntimeException("证书尚未生效", e);
        } catch (CertificateException e) {
            throw new RuntimeException("无效的证书", e);
        }
    }
}
